
//倒计时
import "./../../js/layui/css/layui.css";
require("./../../js/layui/layui.js");

var thisTimer, setCountdown = function ($, y, M, d, H, m, s) {
    var endTime = new Date(y, M || 0, d || 1, H || 0, m || 0, s || 0) //结束日期
        , serverTime = new Date(nowTimeY, nowTimeM, nowTimeD, nowTimeH, nowTimeI, nowTimeS); //假设为当前服务器时间，这里采用的是本地时间，实际使用一般是取服务端的
    clearTimeout(thisTimer);
    countdown(endTime, serverTime, function (date, serverTime, timer) {
        var str = '倒计时:<span>' + date[0] + '</span>天<span>' + date[1] + '</span>时<span>' + date[2] + '</span>分<span>' + date[3] + '</span>秒';
        lay('#timer').html(str);
        var difftime = date[0] + date[1] + date[2] + date[3];
        if (!difftime) {
            location.reload();
            return false;
        }
        thisTimer = timer;
    });
};

function countdown(endTime, serverTime, callback) {
    var type = typeof serverTime === 'function'
        , end = new Date(endTime).getTime()
        , now = new Date((!serverTime || type) ? new Date().getTime() : serverTime).getTime()
        , count = end - now
        , time = [
            Math.floor(count / (1000 * 60 * 60 * 24)) //天
            , Math.floor(count / (1000 * 60 * 60)) % 24 //时
            , Math.floor(count / (1000 * 60)) % 60 //分
            , Math.floor(count / 1000) % 60 //秒
        ];

    if (type) callback = serverTime;

    var timer = setTimeout(function () {
        countdown(endTime, now + 1000, callback);
    }, 1000);

    callback && callback(count > 0 ? time : [0, 0, 0, 0], serverTime, timer);
    if (count <= 0) clearTimeout(timer);
    return timer;
}

export default setCountdown;
